import { defineStore } from 'pinia'

export const useUserAuthStore = defineStore('userAuth', {
  state: () => ({
    isLogin: false,
    token: '',
    userInfo: {
      username: '',
      role: '',
      email: ''
    }
  }),
  actions: {
    login({ token, userInfo }) {
      this.isLogin = true
      this.token = token
      this.userInfo = userInfo
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    logout() {
      this.isLogin = false
      this.token = ''
      this.userInfo = { username: '', role: '', email: '' }
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    initFromStorage() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      if (token && userInfo) {
        this.isLogin = true
        this.token = token
        this.userInfo = JSON.parse(userInfo)
      }
    }
  }
}) 